<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Option;
use App\Enums\OptionType;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;

class OptionController extends AdminController
{
    public array $mobile_hide_columns = ['id', 'sort', 'created_at'];
    public array $normal_hide_columns = ['id'];
    public bool $show_column_selector = false;
    public bool $edit = false;

    public string $create_permission_name = 'option-create';
    public string $delete_permission_name = 'option-delete';


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new Option(), function (Grid $grid) {
            $grid->model()
                ->orderBy('type')
                ->orderBy('sort');
            $grid->column('id');
            $grid->column('type')->display(function ($value) {
                return OptionType::getDescription($value);
            });
            $grid->column('name');
            $grid->column('status')->switch();
            $grid->column('sort');
            $grid->column('created_at')->display(function ($value) {
                return isMobileDevice() ? $value->toDateString() : $value;
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('type')->select(OptionType::asSelectArray());
                $filter->like('name');
            });

            $this->gridCommon($grid);
            $grid->enableDialogCreate();
            $grid->showQuickEditButton();

            //快捷搜索
            $grid->quickSearch(['name'])->placeholder('选项');
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        return Form::make(new Option(), function (Form $form) {
            $form->display('id');
            $form->select('type')->options(OptionType::asSelectArray())->required();
            $form->text('name')->required()->maxLength(100);
            $form->switch('status')->default(true);
            $form->number('sort')->default(100)->min(1)->max(100)->required();

            $form->saving(function (Form $form) {
                if ($form->isCreating() && \App\Models\Option::query()->where('type', $form->input('type'))->where('name', $form->input('name'))->exists()) {
                    return $form->response()->error('选项已存在');
                }
            });
        });
    }
}
